<template>
  <el-form ref="formRef" :rules="rules" :model="form" label-width="100px" class="form"
      v-loading="loading">
    <el-form-item label="姓名" prop="name">
      <el-input v-model="form.name" placeholder="输入姓名"></el-input>
    </el-form-item>
    <el-form-item label="邮箱">
      <el-input v-model="form.email" placeholder="输入邮箱"></el-input>
    </el-form-item>
    <el-form-item label="个人网址">
      <el-input v-model="form.website" placeholder="输入个人网址"></el-input>
    </el-form-item>
    <el-form-item label="地址">
      <el-input v-model="form.address" placeholder="输入地址"></el-input>
    </el-form-item>
    <el-form-item label="状态">
      <el-radio-group v-model="form.status">
        <el-radio :label="1">启用</el-radio>
        <el-radio :label="2">禁用</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="备注" class="flex1">
      <el-input type="textarea" :rows="3" v-model="form.remark" placeholder="输入备注"></el-input>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submit">提交</el-button>
      <el-button @click="$emit('close')">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import {reactive, ref, toRefs, onMounted} from 'vue'
import http from '../../utils/http'
import {ElMessage} from 'element-plus'

export default {
  props: {
    id: {
      type: Number,
      required: false
    }
  },
  emits: ['close'],
  setup(props, {emit}) {
    const state = reactive({
      loading: false,
      form: {
        name: null,
        email: null,
        website: null,
        address: null,
        status: 1,
        remark: null,
      },
      rules: {
        name: [
          {required: true, message: '请输入姓名', trigger: 'blur'},
        ],
      }
    })
    const formRef = ref(null)

    const fetchDetail = async () => {
      console.log('fetchDetail')
      state.loading = true
      const result = await http('/api/users/current')
      state.form = result.data
      state.loading = false
    }
    onMounted(() => {
      if (props.id)
        fetchDetail()
    })

    const submit = async () => {
      try {
        await formRef.value.validate()
      } catch (e) {
        return
      }
      state.loading = true
      const result = await http.put('/api/users', state.form)
      state.loading = false
      if (!result.success)
        return
      ElMessage.success('操作成功')
      emit('close')
    }

    return {
      ...toRefs(state),
      submit,
      formRef,
    }
  },
}
</script>

<style scoped>

</style>
